<template>
  <div class="banner-list">
    <a-page-header
      title="轮播图管理"
      sub-title="管理首页轮播图，包括新增、编辑和删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="轮播图标题">
          <a-input v-model:value="searchForm.title" placeholder="请输入轮播图标题" allowClear />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allowClear
            style="width: 150px"
          >
            <a-select-option :value="0">禁用</a-select-option>
            <a-select-option :value="1">启用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="handleAdd" v-permission="'homepage:banner:add'">
              <template #icon><plus-outlined /></template>新增轮播图
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="tableData" 
        :loading="loading" 
        :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record)" v-permission="'homepage:banner:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除该轮播图吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'homepage:banner:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
            </template>
            <template v-else-if="column.key === 'image'">
              <img v-if="record.imageUrl" :src="`/api${record.imageUrl}`" alt="轮播图" style="width: 120px; height: 60px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'linkType'">
              <span>{{ getLinkTypeText(record.linkType) }}</span>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑轮播图弹窗 -->
    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      @ok="submitForm"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="轮播图标题" name="title">
          <a-input v-model:value="form.title" placeholder="请输入轮播图标题" />
        </a-form-item>
        <a-form-item label="轮播图片" name="imageUrl">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="轮播图" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="链接类型" name="linkType">
          <a-select v-model:value="form.linkType" placeholder="请选择链接类型">
            <a-select-option :value="0">无链接</a-select-option>
            <a-select-option :value="1">内部链接</a-select-option>
            <a-select-option :value="2">外部链接</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="链接地址" name="linkUrl" v-if="form.linkType > 0">
          <a-input v-model:value="form.linkUrl" placeholder="请输入链接地址" />
        </a-form-item>
        <a-form-item label="关联类型" name="relatedType" v-if="form.linkType === 0">
          <a-select v-model:value="form.relatedType" placeholder="请选择关联类型">
            <a-select-option :value="0">无关联</a-select-option>
            <a-select-option :value="1">作品</a-select-option>
            <a-select-option :value="2">活动</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联ID" name="relatedId" v-if="form.linkType === 0 && form.relatedType > 0">
          <a-input-group compact>
            <a-input-number 
              v-model:value="form.relatedId" 
              :min="1" 
              style="width: calc(100% - 90px)" 
              placeholder="请选择关联ID" 
              readonly 
              disabled
            />
            <a-button type="primary" @click="showSelectModal" style="width: 90px">选择{{ form.relatedType === 1 ? '作品' : '活动' }}</a-button>
          </a-input-group>
          <div class="related-tip" v-if="relatedName">
            <span>已选择：{{ relatedName }}</span>
          </div>
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="form.sort" :min="0" style="width: 100%" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  
  <!-- 选择活动/作品弹窗 -->
  <a-modal
    :title="`选择${form.relatedType === 1 ? '作品' : '活动'}`"
    :visible="selectModalVisible"
    @cancel="handleSelectModalCancel"
    :footer="null"
    width="800px"
  >
    <div class="selector">
      <div class="search-bar">
        <a-input
          v-model:value="selectSearchKeyword"
          :placeholder="`请输入${form.relatedType === 1 ? '作品' : '活动'}名称`"
          style="width: 250px; margin-right: 8px"
          @pressEnter="searchItems"
        />
        <a-button type="primary" @click="searchItems">
          <template #icon><search-outlined /></template>搜索
        </a-button>
      </div>
      
      <a-table
        :columns="selectColumns"
        :data-source="selectList"
        :loading="selectLoading"
        :pagination="selectPagination"
        @change="handleSelectTableChange"
        rowKey="id"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <img v-if="record.coverImage" :src="`/api${record.coverImage}`" :alt="`${form.relatedType === 1 ? '作品' : '活动'}封面`" style="width: 60px; height: 30px; object-fit: cover; border-radius: 4px;" />
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getItemStatusColor(record.status)">
              {{ getItemStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="primary" size="small" @click="selectItem(record)">
              选择
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, watch } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import axios from 'axios';

export default defineComponent({
  name: 'BannerList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoadingOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增轮播图');
    const isEdit = ref(false);
    const modalLoading = ref(false);
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const fileList = ref([]);
    const relatedName = ref('');
    
    // 选择活动/作品相关
    const selectModalVisible = ref(false);
    const selectList = ref([]);
    const selectLoading = ref(false);
    const selectSearchKeyword = ref('');
    const selectPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    
    const searchForm = reactive({
      title: '',
      status: undefined,
    });
    
    const form = reactive({
      id: '',
      title: '',
      imageUrl: '',
      linkUrl: '',
      linkType: 0,
      sort: 0,
      status: 1,
      relatedType: 0,
      relatedId: '',
    });
    
    // 监听关联类型变化，重置关联ID和名称
    watch(() => form.relatedType, () => {
      form.relatedId = '';
      relatedName.value = '';
    });
    
    const rules = {
      title: [
        { required: true, message: '请输入轮播图标题', trigger: 'blur' },
        { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' },
      ],
      imageUrl: [
        { required: true, message: '请上传轮播图片', trigger: 'change' },
      ],
      linkUrl: [
        { required: form.linkType > 0, message: '请输入链接地址', trigger: 'blur' },
      ],
      sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' },
      ],
    };
    
    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '轮播图',
        dataIndex: 'imageUrl',
        key: 'image',
        width: 150,
      },
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '链接类型',
        dataIndex: 'linkType',
        key: 'linkType',
        width: 100,
      },
      {
        title: '关联类型',
        dataIndex: 'relatedType',
        key: 'relatedType',
        width: 100,
        customRender: ({ text }) => {
          if (text === 0) return '无关联';
          if (text === 1) return '作品';
          if (text === 2) return '活动';
          return '未知';
        },
      },
      {
        title: '关联ID',
        dataIndex: 'relatedId',
        key: 'relatedId',
        width: 100,
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        width: 80,
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 100,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
      },
    ];

    // 获取轮播图列表
    const fetchData = async () => {
      loading.value = true;
      try {
        const response = await axios.get('/api/banner/page', {
          params: {
            current: currentPage.value,
            size: pageSize.value,
            title: searchForm.title || undefined,
            status: searchForm.status,
          },
        });
        if (response.data.code === 200) {
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          message.error(response.data.message || '获取轮播图列表失败');
        }
      } catch (error) {
        console.error('获取轮播图列表出错:', error);
        message.error('获取轮播图列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 表格分页、排序、筛选变化时触发
    const handleTableChange = (pagination) => {
      currentPage.value = pagination.current;
      pageSize.value = pagination.pageSize;
      fetchData();
    };

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1;
      fetchData();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.title = '';
      searchForm.status = undefined;
      currentPage.value = 1;
      fetchData();
    };

    // 新增轮播图
    const handleAdd = () => {
      isEdit.value = false;
      dialogTitle.value = '新增轮播图';
      resetForm();
      dialogVisible.value = true;
    };

    // 编辑轮播图
    const handleEdit = (record) => {
      isEdit.value = true;
      dialogTitle.value = '编辑轮播图';
      Object.assign(form, record);
      imageUrl.value = record.imageUrl;
      dialogVisible.value = true;
    };

    // 删除轮播图
    const handleDelete = async (id) => {
      try {
        const response = await axios.delete(`/api/banner/${id}`);
        if (response.data.code === 200) {
          message.success('删除成功');
          fetchData();
        } else {
          message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除轮播图出错:', error);
        message.error('删除失败');
      }
    };

    // 重置表单
    const resetForm = () => {
      form.id = '';
      form.title = '';
      form.imageUrl = '';
      form.linkUrl = '';
      form.linkType = 0;
      form.sort = 0;
      form.status = 1;
      form.relatedType = 0;
      form.relatedId = '';
      imageUrl.value = '';
      fileList.value = [];
    };

    // 取消弹窗
    const handleModalCancel = () => {
      dialogVisible.value = false;
      resetForm();
    };

    // 提交表单
    const submitForm = () => {
      formRef.value.validate().then(async () => {
        modalLoading.value = true;
        try {
          let response;
          if (isEdit.value) {
            response = await axios.put(`/api/banner/${form.id}`, form);
          } else {
            response = await axios.post('/api/banner', form);
          }
          
          if (response.data.code === 200) {
            message.success(isEdit.value ? '更新成功' : '添加成功');
            dialogVisible.value = false;
            resetForm();
            fetchData();
          } else {
            message.error(response.data.message || (isEdit.value ? '更新失败' : '添加失败'));
          }
        } catch (error) {
          console.error(isEdit.value ? '更新轮播图出错:' : '添加轮播图出错:', error);
          message.error(isEdit.value ? '更新失败' : '添加失败');
        } finally {
          modalLoading.value = false;
        }
      }).catch(error => {
        console.log('表单验证失败:', error);
      });
    };

    // 上传前校验
    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传JPG或PNG格式的图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
      }
      return isJpgOrPng && isLt2M;
    };

    // 处理上传变化
    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        imageLoading.value = false;
        if (info.file.response.code === 200) {
          imageUrl.value = info.file.response.data;
          form.imageUrl = info.file.response.data;
        } else {
          message.error(info.file.response.message || '上传失败');
        }
      } else if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };

    // 获取链接类型文本
    const getLinkTypeText = (type) => {
      switch (type) {
        case 0: return '无链接';
        case 1: return '内部链接';
        case 2: return '外部链接';
        default: return '未知';
      }
    };
    
    // 选择活动/作品相关方法
    const selectColumns = ref([]);
    
    // 监听关联类型变化，更新表格列定义
    watch(() => form.relatedType, () => {
      if (form.relatedType === 1) {
        // 作品列定义
        selectColumns.value = [
          {
            title: '序号',
            key: 'index',
            width: 80,
            customRender: ({ index }) => index + 1
          },
          {
            title: '封面',
            dataIndex: 'coverImage',
            key: 'cover',
            width: 80,
          },
          {
            title: '作品名称',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
          },
          {
            title: '分类',
            dataIndex: 'categoryName',
            key: 'categoryName',
            width: 120,
          },
          {
            title: '状态',
            key: 'status',
            width: 100,
          },
          {
            title: '操作',
            key: 'action',
            width: 100,
            fixed: 'right',
          }
        ];
      } else if (form.relatedType === 2) {
        // 活动列定义
        selectColumns.value = [
          {
            title: '序号',
            key: 'index',
            width: 80,
            customRender: ({ index }) => index + 1
          },
          {
            title: '封面',
            dataIndex: 'coverImage',
            key: 'cover',
            width: 80,
          },
          {
            title: '活动名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis: true,
          },
          {
            title: '状态',
            key: 'status',
            width: 100,
          },
          {
            title: '时间',
            key: 'time',
            width: 240,
            customRender: ({ record }) => `${record.startTime || '-'} 至 ${record.endTime || '-'}`
          },
          {
            title: '操作',
            key: 'action',
            width: 100,
            fixed: 'right',
          }
        ];
      }
    });
    
    // 显示选择弹窗
    const showSelectModal = () => {
      selectModalVisible.value = true;
      selectSearchKeyword.value = '';
      fetchSelectList();
    };
    
    // 获取选择列表数据
    const fetchSelectList = async (page = 1, pageSize = 10) => {
      try {
        selectLoading.value = true;
        const params = {
          current: page,
          size: pageSize,
        };
        
        // 根据关联类型设置不同的搜索参数
        if (form.relatedType === 1) {
          // 作品搜索
          params.title = selectSearchKeyword.value || undefined;
        } else if (form.relatedType === 2) {
          // 活动搜索
          params.name = selectSearchKeyword.value || undefined;
        }
        
        // 根据关联类型请求不同的API
        const url = form.relatedType === 1 ? '/api/artwork/page' : '/api/activity/page';
        const response = await axios.get(url, { params });
        
        if (response.data.code === 200) {
          selectList.value = response.data.data.records;
          selectPagination.current = page;
          selectPagination.pageSize = pageSize;
          selectPagination.total = response.data.data.total;
        } else {
          message.error(response.data.message || `获取${form.relatedType === 1 ? '作品' : '活动'}列表失败`);
        }
      } catch (error) {
        console.error(`获取${form.relatedType === 1 ? '作品' : '活动'}列表失败:`, error);
        message.error(`获取${form.relatedType === 1 ? '作品' : '活动'}列表失败`);
      } finally {
        selectLoading.value = false;
      }
    };
    
    // 选择表格变化事件
    const handleSelectTableChange = (pagination) => {
      fetchSelectList(pagination.current, pagination.pageSize);
    };
    
    // 搜索项目
    const searchItems = () => {
      fetchSelectList(1, selectPagination.pageSize);
    };
    
    // 取消选择弹窗
    const handleSelectModalCancel = () => {
      selectModalVisible.value = false;
    };
    
    // 选择项目
    const selectItem = (record) => {
      if (form.relatedType === 1) {
        // 选择作品
        form.relatedId = record.id;
        relatedName.value = record.title;
      } else if (form.relatedType === 2) {
        // 选择活动
        form.relatedId = record.id;
        relatedName.value = record.name;
      }
      selectModalVisible.value = false;
    };
    
    // 获取项目状态文本
    const getItemStatusText = (status) => {
      if (form.relatedType === 1) {
        // 作品状态
        switch (status) {
          case 0: return '草稿';
          case 1: return '审核中';
          case 2: return '已发布';
          case 3: return '已拒绝';
          default: return '未知';
        }
      } else if (form.relatedType === 2) {
        // 活动状态
        switch (status) {
          case 0: return '未开始';
          case 1: return '进行中';
          case 2: return '已结束';
          default: return '未知';
        }
      }
      return '未知';
    };
    
    // 获取项目状态颜色
    const getItemStatusColor = (status) => {
      if (form.relatedType === 1) {
        // 作品状态颜色
        switch (status) {
          case 0: return 'default';
          case 1: return 'orange';
          case 2: return 'green';
          case 3: return 'red';
          default: return 'default';
        }
      } else if (form.relatedType === 2) {
        // 活动状态颜色
        switch (status) {
          case 0: return 'blue';
          case 1: return 'green';
          case 2: return 'gray';
          default: return 'default';
        }
      }
      return 'default';
    };

    onMounted(() => {
      fetchData();
    });

    return {
      formRef,
      loading,
      tableData,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      isEdit,
      modalLoading,
      imageUrl,
      imageLoading,
      fileList,
      searchForm,
      form,
      rules,
      columns,
      handleTableChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleModalCancel,
      submitForm,
      beforeUpload,
      handleChange,
      getLinkTypeText,
      // 选择弹窗相关
      selectModalVisible,
      selectList,
      selectLoading,
      selectSearchKeyword,
      selectPagination,
      selectColumns,
      showSelectModal,
      handleSelectModalCancel,
      searchItems,
      selectItem,
      getItemStatusText,
      getItemStatusColor,
      relatedName
    };
  },
});
</script>

<style scoped>
.banner-list {
  background-color: transparent;
}
.search-card {
  margin-bottom: 20px;
}
.avatar-uploader {
  /* display: flex; */
}
.ant-upload-text {
  margin-top: 8px;
}
</style>